const Toast = Swal.mixin({
    toast: true,
    position: 'center',
    background: '#ffc107',
    showConfirmButton: false,
    backdrop: false,
    timer: 3000
});
/**
 * 发布评论的按钮按下触发
 */
function fictionOnPublishButtonClick() {
    var inputHandle = $('#use-content');
    var inputContent = inputHandle.val();
    var idContainerHandle = $('#fiction-id-container');
    var fictionId = idContainerHandle.attr('fictionid');
    var captcha = $('#input-captcha').val();
    var clientHash = $('#input-captcha').realperson('getHash');

    if (inputContent == null || inputContent == '') {
        return;
    }

    // 发布前更换本页的captcha
    $('#input-captcha').realperson('destroy');
    $('#input-captcha').realperson({regenerate:'看不清，更换字符'});

    $.ajax({
        type: 'post',
        async: true,
        data: {"content": inputContent, "fictionid": fictionId, "captcha": captcha, "clientHash": clientHash},
        url: document.location.origin + '/api/publishartilecomment',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                Toast.fire({
                    type: 'success',
                    title: '您的评论发布成功。刷新浏览器即可看到。'
                });
            }
            else {
                Toast.fire({
                    type: 'error',
                    title: '发布发生错误了:' + json.description
                });
            }
        }
    });
}

/**
 * 收藏按钮按下时触发
 * @param target
 */
function fictionOnCollectClick(target) {
    var token = getCookie("token");
    if (token == null || token == '') {
        showDialogToAskLogin('收藏');
        event.stopPropagation();
        return;
    }

    var fictionId = target.parentNode.parentNode.parentNode.getAttribute("fictionid");

    $.ajax({
        type: 'post',
        async: true,
        data: {"id": fictionId},
        url: document.location.origin + '/api/collect',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                var collectOrNot = json.collect;

                if (collectOrNot == true) {
                    fictionOnCollectToggle(target, true);
                }
                else {
                    fictionOnCollectToggle(target, false);
                }
            }
            else {
                console.log(json.description);
            }
        }
    });

    event.stopPropagation();
}

/**
 * 私有方法，被上面的方法使用
 * @param target
 * @param open
 */
function fictionOnCollectToggle(target, open) {
    var children = $(target).children();
    if (open) {
        $(children[0]).removeClass("collect-disable");
        $(children[0]).addClass("collect-enable");
    }
    else {
        $(children[0]).removeClass("collect-enable");
        $(children[0]).addClass("collect-disable");
    }
}

/**
 * 我要评分被点击后触发
 * @param target
 */
function fictionOnIWantToScoreClick(target) {
    //检测登录状态，如果未登录，弹出框让用户登录
    var token = getCookie("token");
    if (token == null || token == '') {
        showDialogToAskLogin('评分');
        event.stopPropagation();
        return;
    }

    var jqueryPopperElement = $('#score-poper-frame');
    jqueryPopperElement.show();

    var htmlPopperElement = jqueryPopperElement.get(0);

    var popper = new Popper(target, htmlPopperElement, {
        placement: 'left',
        flipBehavior: ['left', 'bottom', 'top', 'right'],
        boundariesElement: htmlPopperElement,
    });
}

/**
 *
 */
function fictionOnDiscussClick() {
    var str = window.location.pathname + window.location.search;

    setCookie("pagebeforelogin", str, 0.1);
    window.location.href = document.location.origin + '/login';
}

function fictionShowMessageEditModal() {
    $('#modal-secondary').modal('show');
}

function fictionHideMessageEditModel() {
    $('#modal-secondary').modal('hide');
}

/**
 * 发布信息按钮按下呼叫的方法
 */
function fictionOnSendMessage() {
    var message = $('#fiction-message-content').val().trim();
    var to = $('#fiction-message-creator').text().trim();
    var from = $('#fiction-current_user').text().trim();
    var isLogin = $('#fiction-current_user').attr('isLogin');

    if (isLogin == 'false') {
        return;
    }

    $.ajax({
        type: 'post',
        async: true,
        data: {"from": from, "to": to, "message": message},
        url: document.location.origin + '/api/sendmessage',
        dataType: 'text',
        error: function() {

        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {

            }
            else {
                console.log(json.description);
            }
        }
    });

    fictionHideMessageEditModel();
}

/**
 * 提交分数实际的执行者
 * @param score
 */
function fictionDoScoreSubmit(score) {
    var articleId = $('#fiction-id-container').attr('fictionid');

    $.ajax({
        type: 'post',
        async: true,
        data: {"score": score, "articleid": articleId},
        url: document.location.origin + '/api/submitscore',
        dataType: 'text',
        error: function() {
            toastr.error("服务器错误！请稍后提交");
        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                toastr.success(json.description);
                $('#score-poper-frame').hide();
            }
            else {
                toastr.warning(json.description);
                $('#score-poper-frame').hide();
            }
        }
    });
}

/**
 * 提交评分按钮按下的时候呼叫的方法
 */
function fictionOnSubmitScore() {
    var token = getCookie('token');
    if (token == null || token == '') {
        window.location.href = document.location.origin + '/login';
    }
    else {
        var score = $('#fiction-input-score').val().trim();
        if (score == '') {
            toastr.error('请输入评分后再提交');
        }
        else {
            // 含有小数点的输入
            if (score.indexOf('.') != -1) {
                var parts = score.split('.');
                var first = parts[0];
                var second = parts[1];

                if (first.length == 1 && isAllDigit(first) && second.length == 1 && isAllDigit(second) && parseFloat(score) >= 1 && parseFloat(score) < 10) {
                    fictionDoScoreSubmit(score);
                }
                else if (first.length != 1) {
                    toastr.error('评分如果有小数，整数部分不能大于9');
                }
                else if (!isAllDigit(first)) {
                    toastr.error('小数点前面的部分不是全是数字，请先修改');
                }
                else if (second.length != 1) {
                    toastr.error('评分如果有小数，小数部分必须有、也只能有一个数字');
                }
                else if (!isAllDigit(second)) {
                    toastr.error('小数点后面的部分不是全是数字，请先修改');
                }
                else if (parseFloat(score) < 1) {
                    toastr.error("输入的数字不能小于1");
                }
                else if (parseFloat(score) >= 10) {
                    toastr.error("输入的数字不能大于等于10");
                }
            }
            // 没有小数点
            else {
                if (!isAllDigit(score)) {
                    toastr.error("输入必须是数字");
                }
                else if (score.length > 2 || parseInt(score) > 10 || parseInt(score) < 1) {
                    toastr.error('输入的数字必须小于等于10，大于等于1');
                }
                else {
                    fictionDoScoreSubmit(score);
                }
            }
        }
    }
}

function fictionOnThumpupClick(target) {
    var parentElement = target.parentElement;
    var commentId = target.getAttribute("commentid");

    $.ajax({
        type: 'post',
        async: true,
        data: {"commentid": commentId, "gesture": "up"},
        url: document.location.origin + '/api/commentthumb',
        dataType: 'text',
        error: function() {
            toastr.error("服务器错误！请稍后提交");
        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                var thumbupTextHandle = parentElement.children[2];
                var thumbdownTextHandle = parentElement.children[4];

                thumbupTextHandle.innerText = json.thumbup;
                thumbdownTextHandle.innerText = json.thumbdown;

                $(target).addClass('text-danger');
                var thumbdownIconHandle = parentElement.children[5];
                $(thumbdownIconHandle).removeClass('text-success');
            }
            else {
            }
        }
    });
}

function fictionOnThumpdownClick(target) {
    var parentElement = target.parentElement;
    var commentId = target.getAttribute("commentid");

    $.ajax({
        type: 'post',
        async: true,
        data: {"commentid": commentId, "gesture": "down"},
        url: document.location.origin + '/api/commentthumb',
        dataType: 'text',
        error: function() {
            toastr.error("服务器错误！请稍后提交");
        },
        success: function(data) {
            var json = JSON.parse(data);

            if (json.result == 200) {
                var thumbupTextHandle = parentElement.children[2];
                var thumbdownTextHandle = parentElement.children[4];

                thumbupTextHandle.innerText = json.thumbup;
                thumbdownTextHandle.innerText = json.thumbdown;

                $(target).addClass('text-success');
                var thumbupIconHandle = parentElement.children[3];
                $(thumbupIconHandle).removeClass('text-danger');
            }
            else {
            }
        }
    });
}

function fictionOnReportArticle(target) {
    Swal.fire({
        title: '提交同作者其他作品',
        input: 'text',
        inputAttributes: {
            autocapitalize: 'off'
        },
        showCancelButton: true,
        confirmButtonText: '提交',
        cancelButtonText: '放弃',
    }).then((result) => {
        if (result.value) {
            var name = Swal.getInput().value;

            if (name.trim() == '') {
                return;
            }

            $.ajax({
                type: 'post',
                async: true,
                data: {'name': name},
                url: document.location.origin + '/api/submitlostbook',
                dataType: 'text',
                error: function() {

                },
                success: function(data) {
                    var json = JSON.parse(data);

                    if (json.result == 200) {
                        Toast.fire({
                            type: 'success',
                            title: '提交成功。作品会有编辑审核添加。感谢您的付出',
                        });
                    }
                    else {
                        Toast.fire({
                            type: 'error',
                            title: json.description,
                        });
                    }
                }
            });
            Swal.fire({
                title: '已经提交，衷心感谢。',
            })
        }
    })
}

/**
 * Document ready
 */
$(document).ready(function() {
    var audioLabel = $('#hidden-label-audio');
    if (audioLabel.length > 0) {
        Tipped.create('#audio-icon', audioLabel.text(), {skin:'blue'});
    }
    else {
        Tipped.create('#audio-icon', $('<i/>').html('<label>暂无有声版</label><a href="#">报告</a>'));
    }

    // <#-- 侦听回调，这里是关闭弹出框的 -->
    document.addEventListener("mousedown", function (e) {
        if (!clickInsideElement(e, "p-2")) {
            $('#score-poper-frame').hide();
        }
    });

    // modal
    function alignModal() {
        var modalDialog = $("#modal-dialog-message");
        /* Applying the top margin on modal dialog to align it vertically center */
        modalDialog.css("margin-top", Math.max(0, ($(window).height() - modalDialog.height()) / 2));
    }
    // Align modal when it is displayed
    $("#modal-secondary").on("shown.bs.modal", alignModal);

    // Align modal when user resize the window
    $(window).on("resize", function(){
        $("#modal-secondary:visible").each(alignModal);
    });

    $('#score-poper-frame').hide();

    //
    $.realperson.setDefaults({length: 5});
    $('#input-captcha').realperson({regenerate:'看不清，更换字符'});
});